package com.lagou.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;


public class UpdateConfigurationHelper {

  private CuratorFramework client;

  public UpdateConfigurationHelper() {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    client = CuratorFrameworkFactory.builder()
        .connectString("127.0.0.1:2181")
        .sessionTimeoutMs(50000)
        .connectionTimeoutMs(30000)
        .retryPolicy(retryPolicy)
        .namespace("Configuration")
        .build();
    client.start();
  }

  /**
   * 添加配置信息
   */
  public void setDatabaseData() {
    String nodeName = "/DatabaseConfig";
    try {
      String dbConfiguration = "jdbc.driver=com.mysql.cj.jdbc.Driver\n" +
              "jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8\n" +
              "jdbc.username=root\n" +
              "jdbc.password=devops";
      byte[] bytes = dbConfiguration.getBytes();
      Stat stat = client.checkExists().forPath(nodeName);
      if (stat == null) {
        client.create().withMode(CreateMode.PERSISTENT).forPath(nodeName, bytes);
      } else {
        client.setData().forPath(nodeName, bytes);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 更新配置信息
   */
  public void updateDatabaseData() {
    String nodeName = "/DatabaseConfig";
    try {
      String dbConfiguration = "jdbc.driver=com.mysql.cj.jdbc.Driver\n" +
              "jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8\n" +
              "jdbc.username=root\n" +
              "jdbc.password=devops";
      byte[] bytes = dbConfiguration.getBytes();
      client.setData().forPath(nodeName, bytes);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
